import privateConfig from "./privateConfig"
import { getToken } from '@/utils/auth'
class configFactory {
    constructor(extConfig = {}) {
        const configObj = this.init()
        Object.assign(this, configObj, extConfig)
    }
    init() {
        // 加载public的配置文件
        const publicConfigMap = this.getPublicJson()
        // 先绑定到this，getEncryptionStatus中的urlFormat要用到其中的属性
        Object.assign(this, privateConfig, publicConfigMap)
        const allConfigMap = { ...privateConfig, ...publicConfigMap }

        return this.initField(allConfigMap)
    }
    syncGetReq(path) {
        let xhr = new XMLHttpRequest()
        xhr.open("get", path, false) // 同步请求
        xhr.send()
        return JSON.parse(xhr.responseText)
    }
    //获取公开的配置
    getPublicJson() {
      const timestamp = new Date().getTime();
      console.log("process.env.VUE_APP_BASE_URL: ", process.env.VUE_APP_BASE_URL)
      let baseUrl = process.env.VUE_APP_BASE_URL
      if("/" === baseUrl){
        baseUrl = ''
      }
      return this.syncGetReq(  baseUrl + `/config/index.json?${timestamp}`)
    }
    //初始化字段
    initField(data) {
      // 后端访问地址
      if (data.localHost === true && process.env.NODE_ENV === "production") {
        const { protocol, hostname, port } = document.location;
        let publicPath = process.env.VUE_APP_PUBLICPATH || "";
        publicPath = publicPath.replace("/", "");

        // 判断是否需要拼接端口号
        let localUrl = `${protocol}//${hostname}`;
        if (port && port !== "80" && port !== "443") {
          localUrl += `:${port}`;
        }
        localUrl += publicPath ? "/" + publicPath : "";

        data.APIURL = localUrl + "/";
        console.log(`系统访问地址：${data.APIURL}`);
      }
      return data;
    }
    getLeftPart(str) {
        // 匹配第一条斜杠到第二条斜杠前的字符
        const pattern = /^\/[^/]+/
        const match = str.match(pattern)
        return match ? match[0] : null
    }
    replaceStringWithUrl(url, searchString, targetUrl) {
        const regex = new RegExp(`^${searchString}`)
        const replacedPath = url.replace(regex, targetUrl)
        return replacedPath === url ? url : replacedPath
    }
    //替换路径
    urlFormat = (url, isUrlIncToken = true) => {
        const configObj = this
        url = configObj.APIURL + "/" + url;

        //去除双重斜杠
        url = url.replace(/([^:]\/)\/+/g, "$1")

        // console.log("apiurl: ",url)

        // 路径是否添加token 经过request.js中的请求不加，其他地方调用这个urlFormat默认都会带上Token
        // Todo 下载文件的方式改成调用axios的方式进行下载这里就可以删掉
        if (isUrlIncToken) {
            let authorization = getToken() ;
            if (authorization) {
                let tokenKey = "token"
                if (url.indexOf(tokenKey) === -1) {
                    const joinString = url.includes("?") ? "&" : "?"
                    url += `${joinString}${tokenKey}=${authorization}`
                }
            }
        }
        return url
    }
}

const configInst = new configFactory()

console.log("config: ", configInst)

export default configInst

export { configFactory }
